import { defineConfig, loadEnv } from "vite";
import type { ConfigEnv, UserConfig } from "vite";
import lodash from "lodash";

// configs
import commonConfig from "./config/env/vite.common.config";
import devConfig from "./config/env/vite.dev.config";
import testConfig from "./config/env/vite.test.config";
import prodConfig from "./config/env/vite.prod.config";

const envConfigMap = {
    development: devConfig,
    testing: testConfig,
    production: prodConfig,
} as const;

export default defineConfig(({ command, mode }: ConfigEnv): UserConfig => {
    // 加载环境变量
    const env = loadEnv(mode, process.cwd(), "");
    console.log("command:" + command);
    console.log(`Running in ${mode} mode`);

    const envConfig = envConfigMap[mode as keyof typeof envConfigMap];
    if (!envConfig) {
        throw new Error(`Unknown mode: ${mode}`);
    }

    return lodash.merge(
        {
            // 全局注入环境变量
            define: {
                __APP_ENV__: JSON.stringify(env),
            },
        },
        commonConfig,
        envConfig
    );
});
